<?php
namespace app\controller;

use app\BaseController;
use think\validate\ValidateRule;
use think\facade\Session;
use app\model\Brands as BrModel;

class Brands extends BaseController
{
    protected $middleware = [
        // 对所有方法有效
        '\app\middleware\NavCheck',
        '\app\middleware\UrlCheck',
        '\app\middleware\LoginCheck',
    ];
    public function index()
    {
        return view();
    }

    public function data(){
        $limit = $this->request->param("limit");
        $page = $this->request->param("page");
        $offset = ($page-1)*$limit;

        $user = new BrModel();
        $list = $user->limit($offset,$limit)->select();
        $count = $user->count();


        return json([ "code"=>0,"msg"=>"查询成功","count"=>$count,"data"=>$list]);
    }

    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $user = new BrModel();
            $res =$user ->save($data);
            if($res){
                $this->success("品牌添加成功","index");
            }else{
                $this->error("品牌添加失败");
            }
        }
        return view();
    }

    public function del()
    {
       $id = $this->request->param('id');
       $res = BrModel::where('id',$id)->delete();
       if($res){
           return json(['msg'=>"删除成功",'code'=>0]);
       }
           return json(['msg'=>"删除失败",'code'=>400]);

       }
    public function modify()  //修改方法
    {
        if($this->request->isPost()){
            $data = $this->request->post();
            unset($data['file']);
            if(empty($data['logo'])){
                unset($data['logo']);
            }
            $user = BrModel::find($data['id']);
            $res = $user->save($data);
            if($res){
                $this->success("修改成功","index");
            }else{
                $this->error("修改失败");
            }
        }
        $id = $this->request->param('id');
        $user = BrModel::where('id', $id)->find()->getData();
        return view('add',['list'=>$user]);
    }

    public function update()
    {
        $file = request()->file('file');

        $savename = \think\facade\Filesystem::disk('public')->putFile( '',$file);
        $savename = "/storage/".$savename;

        if(!empty($savename)){
            return json(["code"=>0,"msg"=>$savename]);
        }else{
            return json(["code"=>400,"msg"=>"上传失败"]);
        }

    }
}